import sqlalchemy as sa
from sqlalchemy import orm

from openlbsserver.model import meta

def init_model(engine):
    """Call me before using any of the tables or classes in the model."""

    sm = orm.sessionmaker(autoflush=True, transactional=True, bind=engine)

    meta.engine = engine
    meta.Session = orm.scoped_session(sm)
    
    
t_user = sa.Table('user', meta.metadata,
    sa.Column('id', sa.types.Integer, primary_key=True),
    sa.Column('username', sa.types.String(100)),
    sa.Column('email', sa.types.String(100)),
    sa.Column('password', sa.types.String(100)),
    sa.Column('salt', sa.types.String(100))
)

t_session = sa.Table('session', meta.metadata,
    sa.Column('id', sa.types.Integer, primary_key=True),
    sa.Column('device_id', sa.types.Integer, sa.ForeignKey('device.id')),
    sa.Column('key', sa.types.String(100)),
    sa.Column('expire_time', sa.types.DateTime())
)

t_device = sa.Table('device', meta.metadata,
    sa.Column('id', sa.types.Integer, primary_key=True),
    sa.Column('device_uid', sa.types.String(100)),
    sa.Column('user_id', sa.types.Integer, sa.ForeignKey('user.id'))
)

t_location = sa.Table('location', meta.metadata,
    sa.Column('id', sa.types.Integer, primary_key=True),
    sa.Column('device_id', sa.types.Integer, sa.ForeignKey('device.id')),
    sa.Column('latitude', sa.types.Float),
    sa.Column('longitude', sa.types.Float),
    sa.Column('altitude', sa.types.Float),
    sa.Column('heading', sa.types.Float),
    sa.Column('speed', sa.types.Float),
    sa.Column('date', sa.types.DateTime())
)

class User(object):
    pass
class Device(object):
    pass
class Location(object):
    pass
class UserSession(object):
    pass 
    
orm.mapper(User, t_user)
orm.mapper(Location, t_location, properties=
{
    'device': orm.relation(Device)  
})
orm.mapper(Device, t_device, properties=
{
    'user': orm.relation(User)  
})
orm.mapper(UserSession, t_session, properties=
{
    'device': orm.relation(Device)   
}
)